var express = require("express");
var uunewid = require("uuid");
var router = express.Router();
const moment = require("moment");
var constants = require("../utils/constants");
let log = require("cf-nodejs-logging-support");
log.setLoggingLevel("info");

const { checkEmpty, checkProperty, checkAuth } = require("../utils/utils");
const { ohana } = require("ohana-node-orm");
const tableName = "SAP_JIANGDU_RECOMMENDED_LIST";
const tableNamePolicy = "SAP_JIANGDU_RECOMMENDED_LIST_POLICY";
const ohana_recommend = new ohana(tableName);
const tableFreTable = "SAP_JIANGDU_FREQUENTLY_USED_ENTERPRISES";
const axios = require("axios");


router.get("/getRecommendListStatistics", function (req, res, next) {
  const user = checkAuth(req.user, constants.BASICAUTH);
  if (!user.authCheck) {
    res.sendStatus(403);
  }
  getRecommendListStatistics().then(result => {
    res.send(result)
  })

})
async function getRecommendListStatistics() {
  let ohana_instance = new ohana(tableName);
  let result = await ohana_instance.raw(
    "select TYPE, count(*) as TOTAL from " + tableName + " where TYPE is not NULL group by TYPE order by TOTAL desc "
  );
  var resultData = {};
  resultData.topType = result;
  //monthly growth
  var dateQuery = "select count(*) as TOTAL from " + tableName + " where CREATED_AT between '" + moment().days(-30).format("YYYY-MM") + "' and '" + moment().format("YYYY-MM") + "'"
  console.log(dateQuery)
  var monthlygrowth = await ohana_instance.raw(dateQuery);
  resultData.monthlygrowth = monthlygrowth[0].TOTAL;
  return resultData;
}


router.post("/recommend_policy", function (req, res, next) {
  const user = checkAuth(req.user, constants.BASICAUTH);
  if (!user.authCheck) {
    res.sendStatus(403);
    return;
  }
  const { data } = req.body;
  insertRecommendPolicy(data).then(result => {
    if (result > 0) {
      res.sendStatus(200)
    } else {
      res.sendStatus(400)
    }
  }).catch(err => {
    res.status(500).send(err)
  })

})

router.delete("/recommend_policy", function (req, res, next) {
  const user = checkAuth(req.user, constants.BASICAUTH);
  if (!user.authCheck) {
    res.sendStatus(403);
    return;
  }
  const { data } = req.body;
  deleteRecommendPolicy(data).then(result => {
    if (result > 0) {
      res.sendStatus(200)
    } else {
      res.sendStatus(400)
    }
  }).catch(err => {
    res.status(500).send(err)
  })


})
async function insertRecommendPolicy(data) {
  const con = new ohana(tableNamePolicy); // new ohana('table_name');
  const result = await con.insert(data);
  return result;
}
async function deleteRecommendPolicy(data) {
  const con = new ohana(tableNamePolicy); // new ohana('table_name');
  const result = await con.raw("delete from " + tableNamePolicy + " where USER_ID ='" + data.USER_ID + "' and RECOMMENDED_ID='" + data.RECOMMENDED_ID + "'");
  return result;
}

router.get("/userRecommendList", function (req, res, next) {
  const user = checkAuth(req.user, constants.BASICAUTH);
  if (!user.authCheck) {
    res.sendStatus(403);
    return;
  }
  const { USER_ID } = req.query;
  if (!USER_ID) {
    res.sendStatus(400)
    return;
  }
  var userNew = {
    user_id: USER_ID,
    level: user.level
  }
  getRecommendedEntries("PO", userNew).then(result => {
    res.send(result);
    return;
  })

})
async function getUserRecommendList(USER_ID) {
  const con = new ohana(tableNamePolicy); // new ohana('table_name');
  const result = await con.find({
    USER_ID: USER_ID,
  })
  return result;
}

router.get("/score", function (req, res, next) {
  // #swagger.tags = ['推荐列表']
  // #swagger.summary = '获得政策匹配度'
  /* #swagger.security = [{
               "JiangduJWT": []
  }] */
  /* #swagger.parameters['POLICY_ID'] = {
      description: "policy_",
      required: false,
} */
  const user = checkAuth(req.user, constants.BASICAUTH);
  if (!user.authCheck) {
    res.sendStatus(403);
    return;
  }
  const { POLICY_ID } = req.query
  const payload = {
    USER_ID: user.user_id,
    POLICY_ID: POLICY_ID
  }
  // console.log(payload);
  getScore(payload)
    .then((result) => {
      if (result.length > 0) {
        res.send({ score: result[0].SCORE });
        return;
      } else {
        res.status(200).send({ message: "no score" });
        return;
      }
    })
    .catch((err) => {
      console.log(err)
      // log.error(err);
      res.status(500).send(err);
      return;
    });
});
async function getScore(data) {

  const con = new ohana(tableNamePolicy); // new ohana('table_name');
  const result = await con.find({
    USER_ID: data.USER_ID,
    RECOMMENDED_ID: data.POLICY_ID
  })
  return result;
}


router.get("/recommendForRequest", function (req, res, next) {
  // #swagger.tags = ['推荐列表']
  // #swagger.summary = '根据需求推荐 返回数据'
  /* #swagger.security = [{
               "JiangduJWT": []
  }] */
  const user = checkAuth(req.user, constants.BASICAUTH);
  if (!user.authCheck) {
    res.sendStatus(403);
  }

  recommendForRequest(user.user_id)
    .then((result) => {
      res.status(200).send(result);
    })
    .catch((err) => {
      log.error(err);
      res.status(500).send(err);
    });
});

async function recommendForRequest(USER_ID) {
  // USER_ID = "4cb69428-19f8-11ec-b676-90ccdf01187c"
  // 根据userid获取五种需求
  let fiList = await getJsonDoc(USER_ID, "FI");
  let teList = await getJsonDoc(USER_ID, "TE");
  let taList = await getJsonDoc(USER_ID, "TA");
  let asList = await getJsonDoc(USER_ID, "AS");
  console.log("works")
  let fiRecomList = [];
  for (let index = 0; index < fiList.length; index++) {
    const element = fiList[index];
    let reco = await axios.get(
      constants.recommendURL + "reRequest/" + element.UUID
    );
    fiRecomList = fiRecomList.concat(reco.data.data);
  }
  for (let i = 0, len = fiRecomList.length; i < len; i++) {
    for (let j = i + 1, len = fiRecomList.length; j < len; j++) {
      if (fiRecomList[i].FIN_ID === fiRecomList[j].FIN_ID) {
        fiRecomList.splice(j, 1);
        j--; // 每删除一个数j的值就减1
        len--; // j值减小时len也要相应减1（减少循环次数，节省性能）
      }
    }
  }
  let teRecomList = [];
  for (let index = 0; index < teList.length; index++) {
    const element = teList[index];
    let reco = await axios.get(
      constants.recommendURL + "reRequest/" + element.UUID
    );
    teRecomList = teRecomList.concat(reco.data.data);
  }
  for (let i = 0, len = teRecomList.length; i < len; i++) {
    for (let j = i + 1, len = teRecomList.length; j < len; j++) {
      if (teRecomList[i].TECH_ID === teRecomList[j].TECH_ID) {
        teRecomList.splice(j, 1);
        j--; // 每删除一个数j的值就减1
        len--; // j值减小时len也要相应减1（减少循环次数，节省性能）
      }
    }
  }
  let taRecomList = [];
  for (let index = 0; index < taList.length; index++) {
    const element = taList[index];
    let reco = await axios.get(
      constants.recommendURL + "reRequest/" + element.UUID
    );
    taRecomList = taRecomList.concat(reco.data.data);
  }
  for (let i = 0, len = taRecomList.length; i < len; i++) {
    for (let j = i + 1, len = taRecomList.length; j < len; j++) {
      if (taRecomList[i].TALENT_ID === taRecomList[j].TALENT_ID) {
        taRecomList.splice(j, 1);
        j--; // 每删除一个数j的值就减1
        len--; // j值减小时len也要相应减1（减少循环次数，节省性能）
      }
    }
  }
  let asRecomList = [];
  for (let index = 0; index < asList.length; index++) {
    const element = asList[index];
    let reco = await axios.get(
      constants.recommendURL + "reRequest/" + element.UUID
    );
    asRecomList = asRecomList.concat(reco.data.data);
  }
  for (let i = 0, len = asRecomList.length; i < len; i++) {
    for (let j = i + 1, len = asRecomList.length; j < len; j++) {
      if (asRecomList[i].ASSET_ID === asRecomList[j].ASSET_ID) {
        asRecomList.splice(j, 1);
        j--; // 每删除一个数j的值就减1
        len--; // j值减小时len也要相应减1（减少循环次数，节省性能）
      }
    }
  }

  let ohana_fin = new ohana("SAP_JIANGDU_JINRONGHUIQIS");
  let fin_result = [];
  for (let index = 0; index < fiRecomList.length; index++) {
    const element = fiRecomList[index];
    let result = await ohana_fin.find({ FIN_ID: element.FIN_ID });
    fin_result.push(result[0]);
  }

  let ohana_asset = new ohana("SAP_JIANGDU_ASSETS");
  let asset_result = [];
  for (let index = 0; index < asRecomList.length; index++) {
    const element = asRecomList[index];
    let result = await ohana_asset.find({ ASSET_ID: element.ASSET_ID });
    asset_result.push(result[0]);
  }

  let ohana_tech = new ohana("SAP_JIANGDU_TECH_INNOS");
  let tech_result = [];
  for (let index = 0; index < teRecomList.length; index++) {
    const element = teRecomList[index];
    let result = await ohana_tech.find({ TECH_ID: element.TECH_ID });
    tech_result.push(result[0]);
  }

  let ohana_talent = new ohana("SAP_JIANGDU_TALENTS");
  let talent_result = [];
  for (let index = 0; index < taRecomList.length; index++) {
    const element = taRecomList[index];
    let result = await ohana_talent.find({ TALENT_ID: element.TALENT_ID });
    talent_result.push(result[0]);
  }

  return { fin_result, asset_result, tech_result, talent_result };
}

async function getJsonDoc(userId, type) {
  const ohana_instance = new ohana("SAP_JIANGDU_FREQUENTLY_USED_ENTERPRISES");
  var stringText =
    "select * from  REQUEST_COLLECTION where USER_ID = '" +
    userId +
    "' and TYPE = '" +
    type +
    "'";
  const result = await ohana_instance.raw(stringText);
  let parsedResult = [];
  result.forEach((element) => {
    parsedResult.push(JSON.parse(element.REQUEST_COLLECTION));
  });
  return parsedResult;
}

router.get("/initRecommend", function (req, res, next) {
  // #swagger.tags = ['推荐列表']
  // #swagger.summary = '根据userid初始化推荐五大服务 如果user和五大服务id不重复就插入数据库（否则更新） 如果没有参数用token的USER_ID 如果政策推荐为空会推荐最新的10条政策数据'
  /* #swagger.security = [{
               "JiangduJWT": []
  }] */
  const user = checkAuth(req.user, constants.BASICAUTH);
  if (!user.authCheck) {
    res.sendStatus(403);
  }
  let USER_ID = user.user_id;
  let { USER_ID_QUERY } = req.query;
  if (USER_ID_QUERY) {
    USER_ID = USER_ID_QUERY
  }
  res.sendStatus(200);
//废弃
  // initRecommend(USER_ID)
  //   .then(() => {
  //     res.sendStatus(200);
  //   })
  //   .catch((err) => {
  //     log.error(err);
  //     res.status(500).send(err);
  //   });
});

async function initRecommend(USER_ID) {
  let policy = await axios.get(constants.recommendURL + "recommendPolicy/" + USER_ID);
  let asset = await axios.get(constants.recommendURL + "reCOAssets/" + USER_ID);
  let tech = await axios.get(constants.recommendURL + "reCOTechs/" + USER_ID);
  let talent = await axios.get(constants.recommendURL + "reCOTalents/" + USER_ID);
  let fin = await axios.get(constants.recommendURL + "reCOFins/" + USER_ID);
  if (policy.length == 0) {
    let top10newPo = await ohana_recommend.raw(
      "select top 10 * from SAP_JIANGDU_POLICYS where STATUS = 'on' order by UPDATED_AT desc"
    );
    top10newPo.forEach((element) => {
      let insertData = {};
      insertData.RECOMMENDED_LIST_ID = uunewid.v4();
      insertData.USER_ID = USER_ID;
      insertData.RECOMMENDED_ID = element.POLICY_ID;
      insertData.TYPE = "PO";
      insertData.STATUS = false;
      insertData.COMMENT = "init Recommend";
      insertData.CREATED_AT = moment(new Date()).format("YYYY-MM-DD HH:mm:ss");
      insertData.UPDATED_AT = moment(new Date()).format("YYYY-MM-DD HH:mm:ss");
      ohana_recommend.find({ USER_ID: USER_ID, RECOMMENDED_ID: insertData.RECOMMENDED_ID })
        .then((existData) => {
          if (existData.length == 0) {
            console.log('%crecommendLists.js line:213 insertData', 'color: #007acc;', insertData);
            ohana_recommend.insert(insertData);
          }
          else {
            ohana_recommend.update({ RECOMMENDED_LIST_ID: existData[0].RECOMMENDED_LIST_ID }, { UPDATED_AT: insertData.UPDATED_AT })
          }
        })
    });
  }
  policy.data.data.forEach((element) => {
    let insertData = {};
    insertData.RECOMMENDED_LIST_ID = uunewid.v4();
    insertData.USER_ID = USER_ID;
    insertData.RECOMMENDED_ID = element.PO_ID;
    insertData.TYPE = "PO";
    insertData.STATUS = false;
    insertData.COMMENT = "init Recommend";
    insertData.CREATED_AT = moment(new Date()).format("YYYY-MM-DD HH:mm:ss");
    insertData.UPDATED_AT = moment(new Date()).format("YYYY-MM-DD HH:mm:ss");
    ohana_recommend.find({ USER_ID: USER_ID, RECOMMENDED_ID: insertData.RECOMMENDED_ID })
      .then((existData) => {
        if (existData.length == 0) {
          ohana_recommend.insert(insertData);
        }
        else {
          ohana_recommend.update({ RECOMMENDED_LIST_ID: existData[0].RECOMMENDED_LIST_ID }, { UPDATED_AT: insertData.UPDATED_AT })
        }
      })
  });
  asset.data.data.forEach((element) => {
    let insertData = {};
    insertData.RECOMMENDED_LIST_ID = uunewid.v4();
    insertData.USER_ID = USER_ID;
    insertData.RECOMMENDED_ID = element.ASSET_ID;
    insertData.TYPE = "AS";
    insertData.STATUS = false;
    insertData.COMMENT = "init Recommend";
    insertData.CREATED_AT = moment(new Date()).format("YYYY-MM-DD HH:mm:ss");
    insertData.UPDATED_AT = moment(new Date()).format("YYYY-MM-DD HH:mm:ss");
    ohana_recommend.find({ USER_ID: USER_ID, RECOMMENDED_ID: insertData.RECOMMENDED_ID })
      .then((existData) => {
        if (existData.length == 0) {
          ohana_recommend.insert(insertData);
        }
        else {
          ohana_recommend.update({ RECOMMENDED_LIST_ID: existData[0].RECOMMENDED_LIST_ID }, { UPDATED_AT: insertData.UPDATED_AT })
        }
      })
  });
  tech.data.data.forEach((element) => {
    let insertData = {};
    insertData.RECOMMENDED_LIST_ID = uunewid.v4();
    insertData.USER_ID = USER_ID;
    insertData.RECOMMENDED_ID = element.TECH_ID;
    insertData.TYPE = "TE";
    insertData.STATUS = false;
    insertData.COMMENT = "init Recommend";
    insertData.CREATED_AT = moment(new Date()).format("YYYY-MM-DD HH:mm:ss");
    insertData.UPDATED_AT = moment(new Date()).format("YYYY-MM-DD HH:mm:ss");
    ohana_recommend.find({ USER_ID: USER_ID, RECOMMENDED_ID: insertData.RECOMMENDED_ID })
      .then((existData) => {
        if (existData.length == 0) {
          ohana_recommend.insert(insertData);
        }
        else {
          ohana_recommend.update({ RECOMMENDED_LIST_ID: existData[0].RECOMMENDED_LIST_ID }, { UPDATED_AT: insertData.UPDATED_AT })
        }
      })
  });
  talent.data.data.forEach((element) => {
    let insertData = {};
    insertData.RECOMMENDED_LIST_ID = uunewid.v4();
    insertData.USER_ID = USER_ID;
    insertData.RECOMMENDED_ID = element.TALENT_ID;
    insertData.TYPE = "TA";
    insertData.STATUS = false;
    insertData.COMMENT = "init Recommend";
    insertData.CREATED_AT = moment(new Date()).format("YYYY-MM-DD HH:mm:ss");
    insertData.UPDATED_AT = moment(new Date()).format("YYYY-MM-DD HH:mm:ss");
    ohana_recommend.find({ USER_ID: USER_ID, RECOMMENDED_ID: insertData.RECOMMENDED_ID })
      .then((existData) => {
        if (existData.length == 0) {
          ohana_recommend.insert(insertData);
        }
        else {
          ohana_recommend.update({ RECOMMENDED_LIST_ID: existData[0].RECOMMENDED_LIST_ID }, { UPDATED_AT: insertData.UPDATED_AT })
        }
      })
  });
  fin.data.data.forEach((element) => {
    let insertData = {};
    insertData.RECOMMENDED_LIST_ID = uunewid.v4();
    insertData.USER_ID = USER_ID;
    insertData.RECOMMENDED_ID = element.FIN_ID;
    insertData.TYPE = "FI";
    insertData.STATUS = false;
    insertData.COMMENT = "init Recommend";
    insertData.CREATED_AT = moment(new Date()).format("YYYY-MM-DD HH:mm:ss");
    insertData.UPDATED_AT = moment(new Date()).format("YYYY-MM-DD HH:mm:ss");
    ohana_recommend.find({ USER_ID: USER_ID, RECOMMENDED_ID: insertData.RECOMMENDED_ID })
      .then((existData) => {
        if (existData.length == 0) {
          ohana_recommend.insert(insertData);
        }
        else {
          ohana_recommend.update({ RECOMMENDED_LIST_ID: existData[0].RECOMMENDED_LIST_ID }, { UPDATED_AT: insertData.UPDATED_AT })
        }
      })
  });
}

router.get("/", function (req, res, next) {
  // #swagger.tags = ['推荐列表']
  // #swagger.summary = '获取推荐列表'
  /**
   * #swagger.description = "获得推荐列表 需要JWTtoken。 如果有type参数 根据五大服务 以及JWT token中的user 信息获取对应的推荐列表。
   * ID 为 5大服务的UUID. NAME为各个服务的名称，Description为一些需要显示在消息中的信息。STATUS 为是否为已读还是未读RECOMMENDED_LIST_ID 为该记录在推荐列表的UUID
   * 增加count 参数，可以通过count参数来限制返回的数目...添加没有type 返回全部需要count 限制。"
   */
  /* #swagger.parameters['type'] = {
        description: "PO||AS||TA||TE||FI",
        required: false,
} 
#swagger.parameters['count'] = {
        description: "限制返回条目数",
        required: false}
*/
  /* #swagger.security = [{
               "JiangduJWT": []
  }] */
  const userNew = checkAuth(req.user, constants.BASICAUTH);
  if (!userNew.authCheck) {
    /* #swagger.responses[403] = {
        description: '缺少权限'
                } */
    res.sendStatus(403);
    return;
  }
  const { type } = req.query;
  const { count } = req.query;
  userNew.count = count;
  if (type == undefined) {
    /* #swagger.responses[200] = {
    description: '获得全部数据'
            } */
    getAllEntries(userNew)
      .then((result) => {
        res.send(result);
      })
      .catch((err) => {
        log.error(err);
        res.status(500).send(err);
      });
  } else {
    getRecommendedEntries(type, userNew)
      .then((result) => {
        res.send(result);
      })
      .catch((err) => {
        console.log(err);
        res.status(500).send(err);
      });
  }
});

async function getAllEntries(userNew) {
  // const sqlConn = new ohana(tableName); // new ohana('table_name');
  let allPromise = [];
  allPromise.push(getRecommendedEntries("TA", userNew));
  allPromise.push(getRecommendedEntries("PO", userNew));
  allPromise.push(getRecommendedEntries("FI", userNew));
  allPromise.push(getRecommendedEntries("TE", userNew));
  allPromise.push(getRecommendedEntries("AS", userNew));
  let [taData, poData, fiData, teData, asData] = await Promise.all([...allPromise])
  var result = [];
  result = result.concat(taData, poData, fiData, teData, asData);
  const sortByDate = (arr) => {
    const sorter = (a, b) => {
      return (
        new Date(a.CREATED_AT).getTime() - new Date(b.CREATED_AT).getTime()
      );
    };
    arr.sort(sorter);
  };
  sortByDate(result);
  return result.reverse();
}

async function getRecommendedEntries(type, userNew) {
  const user = new ohana(tableName);
  let sqlString = "";
  switch (type) {
    case "TA":
      sqlString =
        "select T.STATUS as P_STATUS, T.TALENT_ID as ID, T.QRCODE, T.HONOR, T.TALENT_NAME as NAME,T.POSITIONAL_TITLE as DESCRIPTION,RL.STATUS,RL.RECOMMENDED_LIST_ID,RL.CREATED_AT ,'" +
        type +
        '\'as "TYPE",T.TYPE as TTYPE,T.CAREER_YEAR,T.RESEARCH_AREA,T.SPECIAL_TECH,T.WORK_ACHIEVEMENT,T.AVATAR,T.DEGREE from "SAP_JIANGDU_RECOMMENDED_LIST" as RL inner join SAP_JIANGDU_TALENTS as T on RL.RECOMMENDED_ID = T.TALENT_ID  where  RL.USER_ID =\'' +
        userNew.user_id +
        "' and T.STATUS='" +
        constants.STATUSON +
        "'";
      break;
    case "PO":
      sqlString =
        "select RL.RECOMMENDED_ID as RECOMMENDED_LIST_ID,RL.STATUS,P.POLICY_TYPE, P.POLICY_ID,P.RELEASE_DATE,P.DEPARTMENT,P.SUBPOLICY,P.PROCESS_DATE_FROM,P.PROCESS_DATE_TO,P.REPORT_HIGH,P.STATUS as P_STATUS,P.REPORT_HIGH, P.AVATAR,P.POLICY_ID as ID, P.QRCODE, P.POLICY_TITLE as NAME,P.POLICY_URL as DESCRIPTION,RL.R_LEVEL,RL.SCORE,RL.RECOMMENDED_ID,RL.CREATED_AT ,'" +
        type +
        '\' as "TYPE" ,P.POPULARITY from SAP_JIANGDU_RECOMMENDED_LIST_POLICY as RL inner join  "SAP_JIANGDU_POLICYS" as P on RL.RECOMMENDED_ID = P.POLICY_ID  where  RL.USER_ID =\'' +
        userNew.user_id +
        "' and P.STATUS='" + constants.STATUSON + "'";
      break;
    case "FI":
      sqlString =
        "select F.STATUS as P_STATUS, F.AVATAR,F.FIN_ID as ID, F.QRCODE,F.LOAN_METHOD, F.NAME,RL.STATUS,F.DESCRIPTION,RL.RECOMMENDED_LIST_ID,RL.CREATED_AT ,'" +
        type +
        '\' as "TYPE",F.LOAN_QUOTA,F.LOAN_DATE_LOW,F.LOAN_DATE_HIGH,F.RATE_LOW,F.RATE_HIGH from SAP_JIANGDU_RECOMMENDED_LIST as RL inner join "SAP_JIANGDU_JINRONGHUIQIS" as F on RL.RECOMMENDED_ID=F.FIN_ID  where  RL.USER_ID =\'' +
        userNew.user_id +
        "' and F.STATUS='" +
        constants.STATUSON +
        "'";
      break;
    case "TE":
      // sqlString = "select T.COPYRIGHT_TYPE,T.FLAG,T.NAME,T.COMPANY_NAME,T.PATENT_APPLICATION_COUNTRY,T.PATENT_AUTHORIZATION_STATE,T.CREATED_AT,T.QRCODE,T.AVATAR,T.TRADEMARK_REGISTERATION_CODE,T.TRADEMARK_REGISTERATION_DATE,T.COPYRIGHT_REGISTERATION_CODE,T.COPYRIGHT_REGISTERATION_DATE,T.COPYRIGHT_VERSION_CODE,T.COPYRIGHT_AUTHORIZATION_DATE,T.QUALIFICATION_CODE,T.QUALIFICATION_STATUS, RL.STATUS, RL.RECOMMENDED_LIST_ID, RL.CREATED_AT ,'" + type + "'  as \"TYPE\",T.TYPE as \"TTYPE\",T.PATENT_APPLICATION_COUNTRY from SAP_JIANGDU_RECOMMENDED_LIST as RL inner join  \"SAP_JIANGDU_TECH_INNOS\" as T on RL.RECOMMENDED_ID = T.TECH_ID where  RL.USER_ID ='" + userNew.user_id + "'"
      sqlString =
        "select T.STATUS as P_STATUS,T.TYPE as TTYPE,'" +
        type +
        '\' as "TYPE", RL.STATUS, RL.RECOMMENDED_LIST_ID, RL.CREATED_AT, T.TECH_ID as ID, T.* from SAP_JIANGDU_RECOMMENDED_LIST as RL inner join  "SAP_JIANGDU_TECH_INNOS" as T on RL.RECOMMENDED_ID = T.TECH_ID where  RL.USER_ID =\'' +
        userNew.user_id +
        "' and T.STATUS='" +
        constants.STATUSON +
        "'";
      break;
    case "AS":
      sqlString =
        "select T.STATUS as P_STATUS,T.ASSET_ID as ID,T.ASSET_NAME as NAME , T.TRANSACTION_TYPE, T.RENT_PRICE, T.REFERENCE_PRICE, T.QRCODE, T.ASSET_NAME,T.MAKER,T.ASSET_COUNTRY,T.AREA,T.ASSET_COUNT,T.COMPANY_NAME,T.AVATAR,RL.STATUS,T.MAKER as DESCRIPTION, RL.RECOMMENDED_LIST_ID,RL.CREATED_AT ,'" +
        type +
        '\' as "TYPE" from SAP_JIANGDU_RECOMMENDED_LIST as RL inner join  "SAP_JIANGDU_ASSETS" as T on RL.RECOMMENDED_ID = T.ASSET_ID where  RL.USER_ID =\'' +
        userNew.user_id +
        "' and T.STATUS='" +
        constants.STATUSON +
        "'";
      break;
    default:
      break;
  }
  sqlString += "order by RL.CREATED_AT desc"


  var getLevelLimit = "select " + userNew.level + " from GLOBAL_PARAMETER";
  let newRe = await user.raw(getLevelLimit);
  // console.log();
  var limit = {};
  try {
    limit = JSON.parse(newRe[0][userNew.level])

  } catch (error) {
    limit = {fin:99,tech:99,talent:99,asset:99,policy:99}
  }
  // var limit = JSON.parse(newRe[0][userNew.level])
  switch (type) {
    case "FI":
      userNew.count = limit.fin;
      break;
    case "TE":
      userNew.count = limit.tech;
      break;
    case "TA":
      userNew.count = limit.talent;
      break;
    case "AS":
      userNew.count = limit.asset;
      break;
    case "PO":
      userNew.count = limit.policy;
      break;

    default:
      break;
  }

  if (userNew.count) {
    sqlString +=
      " limit " + parseInt(userNew.count);
  }
  let resultData = await user.raw(sqlString);
  if (type == "PO") {
    let allPromise = [];
    for (let index = 0; index < resultData.length; index++) {
      const element = resultData[index];
      allPromise.push(element.TAGS = await getPolicyTagsByCate(element.POLICY_ID))
    }
    Promise.all([...allPromise])
  }
  return resultData;
}


router.get("/getTopPolicies", function (req, res, next) {
  // #swagger.tags = ['推荐列表']
  // #swagger.summary = '获取置顶的政策'
  /**
   * #swagger.description = "获得置顶的政策"
   */
  /* #swagger.security = [{
               "JiangduJWT": []
  }] */
  const userNew = checkAuth(req.user, constants.BASICAUTH);
  if (!userNew.authCheck) {
    /* #swagger.responses[403] = {
        description: '缺少权限'
                } */
    res.sendStatus(403);
    return;
  }
  getTopPolicies().then(results => {
    res.send(results);
  })
});

async function getTopPolicies() {
  const policyConn = new ohana(constants.POLICYTABLE);
  var results = await policyConn.find({ PRIORITY: 9, STATUS: constants.STATUSON });
  results.map(one => {
    delete one.CDATA;
    one.ID = one.POLICY_ID;
    one.NAME = one.POLICY_TITLE;
    one.DESCRIPTION = one.POLICY_URL;
  })
  let allPromise = [];
  for (let index = 0; index < results.length; index++) {
    const element = results[index];
    allPromise.push(element.TAGS = await getPolicyTagsByCate(element.POLICY_ID))
  }
  Promise.all([...allPromise])
  return results;

}
async function getPolicyTagsByCate(data) {
  const policyTag = new ohana(tableName);
  let sqlString =
    "SELECT TAG.* FROM SAP_JIANGDU_TAGS AS TAG LEFT JOIN SAP_JIANGDU_TAG_POLICYS AS J ON TAG.TAG_ID = J.TAG_ID_TAG_ID WHERE J.POLICY_ID_POLICY_ID = '" +
    data +
    "'";
  const result = await policyTag.raw(sqlString);
  let a = { name: "industry", data: [] };
  let b = { name: "热门产业", data: [] };
  let c = { name: "政策关键词", data: [] };
  let d = { name: "行业小类", data: [] };
  let e = { name: "发文部门", data: [] };
  result.map((one) => {
    if (one.TAG_CATEGORY == a.name) {
      a.data.push(one);
    } else if (one.TAG_CATEGORY == b.name) {
      b.data.push(one);
    } else if (one.TAG_CATEGORY == c.name) {
      c.data.push(one);
    } else if (one.TAG_CATEGORY == d.name) {
      d.data.push(one);
    } else if (one.TAG_CATEGORY == e.name) {
      e.data.push(one);
    }
  });
  return { a, b, c, d, e };
}

router.post("/", function (req, res, next) {
  // #swagger.tags = ['推荐列表']
  // #swagger.summary = '新建推荐列表'
  /* #swagger.security = [{
               "JiangduJWT": []
  }] */
  /*	#swagger.requestBody = {
            required: true,
            content: {
                "application/json": {
                    schema: {
                        $ref: "#/definitions/recommendList"
                    }  
                },
            }
    } */
  const { data } = req.body;
  if (data.length > 0) {
    data.map((one) => {
      one.RECOMMENDED_LIST_ID = uunewid.v4();
    });
    insertData(data)
      .then((result) => {
        if (result == data.length) {
          res.sendStatus(200);
        } else {
          res.send(500);
        }
      })
      .catch((err) => {
        log.error(err);
        res.status(500).send(err);
      });
  }
  log.info(uunewid.v4());
  log.info(data);
});

// router.post("/notices", function (req, res, next) {
//   // #swagger.tags = ['推荐列表']
//   // #swagger.summary = ？？？？？？？
//   /* #swagger.security = [{
//                "JiangduJWT": []
//   }] */
//   /*	#swagger.requestBody = {
//             required: true,
//             content: {
//                 "application/json": {
//                     schema: {
//                         $ref: "#/definitions/recommendList"
//                     }
//                 },
//             }
//     } */
//   const queryData = req.query;
//   const recommendLists = new ohana(tableName); // new ohana('table_name');
//   if (queryData == null) {
//     recommendLists.find().then((result) => {
//       res.send(result);
//     });
//   } else {
//     recommendLists.find(queryData).then(async (result) => {
//       const rets = await Promise.all(
//         result.map(async (one) => {
//           content = await getTypedContent(one.TYPE, one.RECOMMENDED_ID);
//           for (var obj in content) {
//             one[obj] = content[obj];
//           }
//         })
//       );
//       log.info(result);
//       res.send(result);
//     });
//   }
// });

// get count

router.post("/getUnreadNoticeCount", function (req, res, next) {
  // #swagger.tags = ['推荐列表']
  // #swagger.summary = '获取未读的消息数量'
  // #swagger.description = '获取未读的消息数量 需要JWT token。无需额外参数。传参数 STATUS = false'
  /* #swagger.security = [{
               "JiangduJWT": []
  }] */
  /*	#swagger.requestBody = {
            required: true,
            content: {
                "application/json": {
                    schema: {
                        $ref: "#/definitions/recommendList"
                    }  
                },
            }
    } */
  const { data } = req.body;
  const userNew = checkAuth(req.user, constants.BASICAUTH);
  if (!userNew.authCheck) {
    /* #swagger.responses[403] = {
    description: '缺少权限'
            } */
    res.send(403);
    return;
  }
  data.USER_ID = userNew.user_id;
  data.STATUS = false;
  countUnreadNotice(data)
    .then((result) => {
      if (result >= 0) {
        res.send({ count: result });
      } else {
        res.sendStatus(500);
      }
    })
    .catch((err) => {
      log.error(err);
      res.status(500).send(err);
    });
});

router.post("/toggleNotice", function (req, res, next) {
  // #swagger.tags = ['推荐列表']
  // #swagger.summary = '设置消息已读或者未读 如果有参数Type 值为all'
  // #swagger.description= '如果body有参数type 值为PO||AS等 则全部的该类型数据为已读或者未读 否则就是单挑数据设置为已读或者未读需要传入STATUS值 修改单条数据时需要不要传type 参数'
  /**   #swagger.security = [{
                 "JiangduJWT": []
    }] */
  /*	#swagger.requestBody = {
            required: true,
            content: {
                "application/json": {
                    schema: {
                        $ref: "#/definitions/recommendList_toggleNotice"
                    }  
                },
            }
    } */

  //checkData(res, req.body.data);
  const { data } = req.body;
  const userNew = checkAuth(req.user, constants.BASICAUTH);
  if (!userNew.authCheck) {
    /* #swagger.responses[403] = {
        description: '缺少权限'
                } */
    res.sendStatus(403);
    return;
  }
  let checkResult = checkEmpty(["STATUS"], data);
  if (!checkResult.noUndefined) {
    res.send({ message: checkResult.msg });
  }
  data.USER_ID = userNew.user_id;
  if (data.type) {
    updateStatus(data)
      .then((result) => {
        if (result > 0) {
          res.sendStatus(200);
          /* #swagger.responses[200] = {
      description: '成功'
              } */
        } else {
          log.info(result);
          res.status(400).send({ message: "找不到该条数据" });
          /* #swagger.responses[400] = {
      description: '客户端请求错误'
              } */
        }
      })
      .catch((err) => {
        log.error(err);
        res.status(500).send(err);
      });
  } else {
    updateSingleNoticeStatus(data)
      .then((result) => {
        log.info(result);
        console.log(result);
        if (result == 1) {
          res.sendStatus(200);
          /* #swagger.responses[200] = {
      description: '成功'
              } */
        } else {
          res.status(400).send({ message: "没有该数据" });
          /* #swagger.responses[500] = {
      description: '数据库错误'
              } */
        }
      })
      .catch((err) => {
        log.error(err);
        res.status(500).send(err);
      });
  }
});

router.put("/", function (req, res, next) {
  // #swagger.tags = ['推荐列表']
  // #swagger.summary = '修改推荐列表'
  /* #swagger.security = [{
               "JiangduJWT": []
  }] */
  /*	#swagger.requestBody = {
            required: true,
            content: {
                "application/json": {
                    schema: {
                        $ref: "#/definitions/recommendList"
                    }  
                },
            }
    } */
  //checkData(res, req.body.data);
  const { data } = req.body;
  updateMessage(data)
    .then((result) => {
      log.info(result);
      if (result == 1) {
        res.sendStatus(200);
      } else {
        res.send(500);
      }
    })
    .catch((err) => {
      log.error(err);
      res.status(500).send(err);
    });
});

async function countUnreadNotice(body) {
  const policy = new ohana(tableName); // new ohana('table_name');
  const result = await policy.count("RECOMMENDED_LIST_ID", body);
  // console.log("good")
  // console.log(body)
  const realPolicy = new ohana(tableNamePolicy);
  const resultPolicy = await realPolicy.raw("select count(*) as total from " + tableNamePolicy + " where STATUS is null and USER_ID = '" + body.USER_ID + "' ");
  // console.log(resultPolicy);
  const realNumber = result[0]["COUNT(RECOMMENDED_LIST_ID)"] + resultPolicy[0]["TOTAL"];
  return realNumber;
}

async function insertData(body) {
  const user = new ohana(tableName); // new ohana('table_name');
  const freCompany = new ohana(tableFreTable);
  const result = await user.batchInsert(body);
  body.map((one) => {
    log.info(one);
    freCompany
      .findOne({ ENTERPRISE_ID_USER_ID: one.USER_ID })
      .then((result) => {
        log.info(result);
        if (result.length == 0) {
          freCompany.insert({ ENTERPRISE_ID_USER_ID: one.USER_ID, COUNT: 1 });
        } else {
          freCompany.update(
            { ENTERPRISE_ID_USER_ID: one.USER_ID },
            { COUNT: result[0].COUNT + 1 }
          );
        }
        // result.COUNT = result.COUNT + 1;
        // freCompany.update({ ENTERPRISE_ID_USER_ID: result.USER_ID }, { COUNT: result.COUNT })
      })
      .catch((err) => {
        log.error(err);
        res.status(500).send(err);
      });
  });
  return result;
}

async function updateSingleNoticeStatus(body) {
  const otherpolicy = new ohana(tableName); // new ohana('table_name');
  const policy = new ohana(tableNamePolicy);
  let result, result1 = 0;
  console.log(body);
  result = await policy.update(
    {
      USER_ID: body.USER_ID,
      RECOMMENDED_ID: body.RECOMMENDED_LIST_ID,
    },
    { STATUS: body.STATUS }
  );
  result1 = await otherpolicy.update(
    {
      RECOMMENDED_LIST_ID: body.RECOMMENDED_LIST_ID,
    },
    { STATUS: body.STATUS }
  );
  return result + result1;
}
async function updatePOStatus(body) {
  const sqlConn = new ohana(tableNamePolicy); // new ohana('table_name');
  var payload = {
    USER_ID: body.USER_ID,
    TYPE: body.type,
  };
  if (body.type == "all") {
    delete payload.TYPE;
  }
  const result = await sqlConn.update(payload, { STATUS: body.STATUS });
  return result;
}
async function updateStatus(body) {
  const sqlConn = new ohana(tableName); // new ohana('table_name');
  var payload = {
    USER_ID: body.USER_ID,
    TYPE: body.type,
  };
  if (body.type == "all") {
    delete payload.TYPE;
  }
  const result = await sqlConn.update(payload, { STATUS: body.STATUS });
  return result;
}
async function updateMessage(body) {
  const policy = new ohana(tableName); // new ohana('table_name');
  const result = await policy.update(
    {
      MESSAGE_ID: body.MESSAGE_ID,
    },
    body
  );
  return result;
}

async function getTypedContent(TYPE_TYPE, ID_ID) {
  data = {};
  switch (TYPE_TYPE) {
    case "PO":
      table_name = "SAP_JIANGDU_POLICYS";
      search = new ohana(table_name);
      result = await search.findOne({ POLICY_ID: ID_ID });
      data.TITLE = result[0].POLICY_TITLE;
      data.URL = result[0].POLICY_URL;
      return data;

    case "TA":
      table_name = "SAP_JIANGDU_TALENTS";
      search = new ohana(table_name);
      result = await search.findOne({ TALENT_ID: ID_ID });
      return result;

    case "FI":
      table_name = "SAP_JIANGDU_JINGRONGHUQIS";
      search = new ohana(table_name);
      result = await search.findOne({ FIN_ID: ID_ID });
      return result;

    case "AS":
      table_name = "SAP_JIANGDU_ASSETS";
      search = new ohana(table_name);
      result = await search.findOne({ FIN_ID: ID_ID });
      return result;

    case "TE":
      table_name = "SAP_JIANGDU_INNOS";
      search = new ohana(table_name);
      result = await search.findOne({ FIN_ID: ID_ID });
      return result;
  }
}

router.get("/getEntries", function (req, res, next) {
  // #swagger.tags = ['推荐列表']
  // #swagger.summary = '逛大厅专用-获得随机的五大服务数据'
  // #swagger.description= '获得随机的五大服务'
  /* #swagger.security = [{
               "JiangduJWT": []
  }] */

  let { count } = req.query;
  if (!count) {
    count = 10;
  }
  const user = new ohana(tableName); // new ohana('table_name');
  let sqlText =
    'select * from "JIANGDU_ALL_SERVICES" where STATUS = \'' +
    constants.STATUSON +
    "' order by Rand() limit " +
    count;
  user
    .raw(sqlText)
    .then((result) => {
      if (result.length > 0) {
        res.send(result);
      } else {
        res.sendStatus(500);
      }
    })
    .catch((err) => {
      log.error(err);
      res.status(500).send(err);
    });
});

//---------------------delete-------------------------------------------------------------
router.delete("/", function (req, res, next) {
  // #swagger.tags = ['推荐列表']
  // #swagger.summary = '删除推荐根据'
  // #swagger.description= '删除单个推荐根据 RECOMMENDED_LIST_ID; 删除全部 type 为all值；删除某个类型的推荐 type值为PO'
  /* #swagger.security = [{
               "JiangduJWT": []
  }] */
  /*	#swagger.requestBody = {
          required: true,
          content: {
              "application/json": {
                  schema: {
                      $ref: "#/definitions/rl_delete"
                  }  
              },
          }
  } */
  const userNew = checkAuth(req.user, constants.BASICAUTH);
  log.info(userNew.authCheck);
  if (!userNew.authCheck) {
    /* #swagger.responses[403] = {
        description: '缺少权限'
                } */
    res.sendStatus(403);
    return;
  }
  const { data } = req.body;
  const sqlConn = new ohana(tableName); // new ohana('table_name');
  let sqlText = "";
  if (data.type) {
    sqlText =
      'delete from "' +
      tableName +
      "\" where USER_ID = '" +
      userNew.user_id +
      "'";
    if (data.type != "all") {
      sqlText += " and TYPE = '" + data.type + "'";
    }
  } else {
    sqlText =
      'delete from "' +
      tableName +
      "\" where RECOMMENDED_LIST_ID = '" +
      data.RECOMMENDED_LIST_ID +
      "'";
  }
  sqlConn
    .raw(sqlText)
    .then((result) => {
      if (result > 0) {
        res.sendStatus(200);
      } else {
        res.send({ message: "没有该数据" });
      }
    })
    .catch((err) => {
      log.error(err);
      res.status(500).send(err);
    });
});
//---------------------delete-------------------------------------------------------------

router.get("/count", function (req, res, next) {
  // #swagger.tags = ['推荐列表']
  // #swagger.summary = '获取推荐的统计数据'
  /**
   * #swagger.description = "获得推荐的统计信息.无参数是所有的条目数，如果有type 则是根据type 的条目数。USER信息需要JWT token"
   * "
   */
  /* #swagger.parameters['type'] = {
        description: "PO||AS||TA||TE||FI",
        required: false,
} */
  /* #swagger.security = [{
               "JiangduJWT": []
  }] */
  const userNew = checkAuth(req.user, constants.BASICAUTH);
  if (!userNew.authCheck) {
    /* #swagger.responses[403] = {
        description: '缺少权限'
                } */
    res.sendStatus(403);
    return;
  }
  const { type } = req.query;
  const sqlConn = new ohana(tableName); // new ohana('table_name');
  if (type == undefined) {
    sqlConn
      .count("RECOMMENDED_LIST_ID", { USER_ID: userNew.user_id })
      .then((result) => {
        const resultObject = result[0];
        if (result.length > 0) {
          res.send({
            count: resultObject[Object.keys(resultObject)[0]],
          });
        }
      })
      .catch((err) => {
        log.error(err);
        res.status(500).send(err);
      });
  } else {
    sqlConn
      .count("RECOMMENDED_LIST_ID", { USER_ID: userNew.user_id, TYPE: type })
      .then((result) => {
        if (result.length > 0) {
          const resultObject = result[0];
          res.send({
            count: resultObject[Object.keys(resultObject)[0]],
            type: type,
          });
        } else {
          res.send({ message: "无数据" });
        }
      })
      .catch((err) => {
        log.error(err);
        res.status(500).send(err);
      });
  }
});

module.exports = router;
